const path = require('path')
const glob = require('glob')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const publicPath = './'

function generateUUID() {
	 var s = [];
	  var hexDigits = "0123456789abcdef";
	  for (var i = 0; i < 36; i++) {
	    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	  }
	  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	  s[8] = s[13] = s[18] = s[23] = "-";
	  
	  var uuid = s.join("");
	  return uuid;
};
// 入口文件
const entry = {}
// 入口文件对应的模板
const entryTemplate = []

exports.entry = () => {
	seekAllFile()
	setEntryTemplate()
	return {
		entry,
		entryTemplate
	}
}

// 得到pages文件夹下所有入口文件(支持无限嵌套)
const seekAllFile = (parent = 'pages/*') => {
	const fileList = glob.sync(path.resolve(__dirname, parent))
	if (fileList.length > 0) {
		fileList.forEach(file => {
			const regJs = file.match(/.*\/(.*js)/i)
			if (regJs !== null && regJs[1]) {
				const jsName = regJs[1]
				const key = parent.replace(/pages\//, '').replace(/\/\*/, '')
				entry[key] = publicPath + parent.replace(/\*/, '') + jsName
			} else {
				const parentPath = parent.replace(/\*/, '')
				const reg = new RegExp(parentPath + '(.*)', 'i')
				const folder = file.match(reg)[1]
				if (!file.match(/.*\/(.*?)\..*/)) {
					// console.log(parentPath,file)
					seekAllFile(parentPath + folder + '/*')
				}
			}
		})
	} else {
		return
	}
}

// 设置入口文件的模板文件(附加功能)
const setEntryTemplate = () => {
	console.log(entry,'+++++++++++++++++')
	Object.keys(entry).forEach(key => {
		let arr = ['home','about','news','login','join']
		let type = false
		
		arr.forEach(item=>{
			if(entry[key].indexOf(item) > -1){
				type = true
			}
		})
		if(!type){
			return false
		}
		// let filename = key.split('_')[0]
		
		// let p = entry[key].replace(`/${filename}.js`, '.html').replace(/\.\/pages\//, '')
		// // console.log(p,'---------------------',entry[key])
		entryTemplate.push(new HtmlWebpackPlugin({
			template: entry[key].replace(/\.js/, '.html'),
			filename: key + '.html',
			chunks: [key],
			inject: 'body',
			minify: false
		}))
	})
}
